package edu.xmu.software.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import edu.xmu.software.pojo.Item;
import edu.xmu.software.dao.ItemDAO;

public class SearchItemsController extends AbstractController {

	private ItemDAO itemDAO;
	
	public void setItemDAO(ItemDAO itemDAO) {
		this.itemDAO = itemDAO;
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String keyword = request.getParameter("keyword");
		//System.out.println("keyword a: " + keyword);
		keyword = new String(keyword.getBytes("iso-8859-1"), "utf-8");
		//System.out.println("keyword c: " + keyword);
		List<Item> itemsList = null;
		Map<String, Object> retValue = new HashMap<String, Object>();
		itemsList = itemDAO.findItemsByKeyword(keyword);
		
		retValue.put("keyword", keyword);
		
		if (itemsList.size() == 1) {
			if (itemsList.get(0).getTitle().equals(keyword)) {
				retValue.put("item", itemsList.get(0));
				return new ModelAndView("view_item", retValue);
			}
		}
		
		retValue.put("itemslist", itemsList);
		return new ModelAndView("s_results", retValue);
	}

}
